import angular from 'angular'
import '../../../public/js/plugins/angular-ui'
import "../../../public/js/plugins/select2/select2"
import "../../../public/js/myservice/contract/contract-common"
import "../../../public/js/myservice/contract/contract-menu"
import myMath from "../../../public/js/myservice/common/my-math"
import util from "@yunke/core/util"
import moment from "moment"
import $ from 'jquery'
import { map, findIndex, chain, includes, isEmpty, get } from 'lodash'
import serverName from './base.server'
import modal from '@yunke/angular-ui/lib/yunkeModal'
import { settlementType, contractType } from '../constant'
import { isSpecial } from "../util"

const editPrincipal = require("./base-inc-edit-project.html")

const apiPrefix = window.G_CONFIG.api_prefix;

const productName = "产品租用金额"
const productNameAdv = "广告投放金额"
const payloadName = "交付金额"
const payloadNameAdv = "广告投放服务费"

angular.module('ContractBase', ['select2', 'ngUI', 'ContractCommonService', 'ContractMenu', modal])
    .controller('contractBaseCtrl', [
        '$scope',
        '$timeout',
        '$location',
        '$routeParams',
        'contractCommonService',
        serverName,
        'yunkeModal',
        ($scope, $timeout, $location, $routeParams, contractCommonService, contractServerName, yunkeModal) => {
            /**
             * 合同性质为云客签约-直属区域/云客签约-联营区域 时候
             * 签约金额 = 收入金额
             * @param contractNature  合同性质
             */
            let needUpdateIncomeAmountFromSignVal = false
            function incomeWithSign(contractNature) {
                //云客签约-直属区域/云客签约-联营区域/云客直销
                const limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
                needUpdateIncomeAmountFromSignVal = includes(limitContractArr, contractNature)
            }
            $scope.$watch('contractBaseInfo.sign_amount', function (signVal) {
                if (needUpdateIncomeAmountFromSignVal) {
                    $scope.contractBaseInfo.income_amount = signVal;
                }
            });
            //合同基本信息
            $scope.isLimitContractNature = false;
            $scope.contractBaseInfo = {
                customer_property: 0,
                attribute_name: "false,false,false",
                contract_status: 0,
                is_cancelled: 0,
                give_work_day: 0,
                develop_work_day: 0,
                implement_work_day: 0
            };
            //产品列表
            $scope.projects = [];


            //先加载下拉框
            // 合同性质下拉框处理
            $scope.ddlConfigContractNature = {
                allowClear: false,
                data: [],
                placeholder: '合同性质',
                onchange2(selected) {
                    //获取公司下拉信息
                    contractCommonService.actionGetContractCompanyList(selected.id, function (data) {
                        const isCompanyValid = findIndex(data, ['company_id', $scope.contractBaseInfo.company_id]) !== -1
                        $scope.ddlConfigCompany.data = map(data, ({ company_id, company_name }) => ({
                            id: company_id,
                            text: company_name
                        }));
                        if (!isCompanyValid) {
                            //切换性质时清空签署公司
                            $scope.contractBaseInfo.company_id = null;
                        }
                        $scope.$applyAsync();
                    });
                    //若直属区域 ,增加交付信息 菜单
                    //contractMenuService.menuInit(selected.id);
                    //绑定签约金额和收入金额
                    incomeWithSign(selected.id);
                }
            };

            //获取合同性质列表
            contractCommonService.getContractNatures(function (data) {
                //隐藏 明源签约-联营区域:7f828b1b-fce8-11e4-bed8-00155d02c832,
                //    联营签约-明源结算:7f84cfad-fce8-11e4-bed8-00155d02c832
                $scope.ddlConfigContractNature.data = chain(data)
                    .reject(['property_id', '7f84cfad-fce8-11e4-bed8-00155d02c832'])
                    .map(({ property_id, property_name }) => ({ id: property_id, text: property_name }))
                    .value();
                $scope.$applyAsync();
            });


            // 合同签署公司下拉框处理
            $scope.ddlConfigCompany = {
                allowClear: false,
                data: [{
                    id: 1,
                    text: '明源云客'
                }],
                placeholder: '合同签署公司'
            };

            // 合同类别下拉框处理
            $scope.ddlConfigContractCategory = {
                allowClear: false,
                data: [{
                    id: 1,
                    text: '云客租用服务合同'
                }],
                placeholder: '合同类别'
            };

            //获取类别下拉信息
            contractCommonService.getContractCategories(function (data) {
                $scope.ddlConfigContractCategory.data = map(data, ({ category_id, category_name }) => ({ id: category_id, text: category_name }));
                $scope.$applyAsync();
            });


            // 合同小类下拉框处理
            $scope.ddlConfigContractSmallClass = {
                allowClear: false,
                data: [],
                placeholder: '合同小类'
            };
            $scope.$watch("contractBaseInfo.littler_category_id", (id) => {
                const isRent = id === "62f81rt6-fcf4-11e4-bed8-00155d02c832"
                $scope.productName = isRent ? productNameAdv : productName
                $scope.payloadName = isRent ? payloadNameAdv : payloadName
            })
            // 合同大类下拉框处理
            $scope.ddlConfigContractBigClass = {
                allowClear: false,
                data: [],
                placeholder: '合同大类',
                onchange2(item) {
                    if (!item || !item.id) {
                        return;
                    }
                    contractCommonService.getContractSmallClass(item.id, function (data) {
                        let curSmallClass = null;
                        $.each(data, function (i, d) {
                            if (d.littler_category_id == $scope.contractBaseInfo.littler_category_id) {
                                curSmallClass = {
                                    id: d.littler_category_id,
                                    text: d.littler_category_name
                                };
                            }
                        });
                        $scope.ddlConfigContractSmallClass.data = map(data, ({ littler_category_id, littler_category_name }) => ({ id: littler_category_id, text: littler_category_name }));

                        $scope.$applyAsync();
                        setTimeout(function () {
                            $('#idSmallClass').length && $('#idSmallClass').data('select2').updateSelection(curSmallClass);
                        }, 0);

                    })
                }
            };

            //获取大类下拉信息
            contractCommonService.getContractBigClass(function (data) {
                const ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({
                        id: d.big_category_id,
                        text: d.big_category_name
                    });
                });
                $scope.ddlConfigContractBigClass.data = ddlData;
                $scope.$applyAsync();
            });

            // 合同签约地区下拉框处理
            $scope.ddlConfigContractSignArea = {
                allowClear: false,
                data: [{
                    id: 1,
                    text: '北京'
                }],
                placeholder: '合同签约地区'
            };
            //获取签约地区下拉信息
            contractCommonService.getContractAreas(function (data) {
                const ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({
                        id: d.regionId,
                        text: d.regionName
                    });
                });
                $scope.ddlConfigContractSignArea.data = ddlData;
                $scope.$applyAsync();
            });

            // 产品下拉框数据
            $scope.ddlConfigProjectsData = [];
            //合同主责人下拉数据
            $scope.ddlConfigPrincipalsData = [];
            // 其他产品下拉框数据
            $scope.ddlConfigOtherProjectsData = [];

            //获取产品下拉信息
            contractCommonService.getProducts(function (data) {
                const ddlData = [];
                $.each(data, function (i, d) {
                    var  unit = '';
                    if(!isEmpty(d.applicationPrices)){
                        unit = ' + ' + d.applicationPrices[0].unit;
                    }
                    ddlData.push($.extend({}, {
                        id: d.application_id,
                        text: d.application_name + unit
                    }, d));
                });
                $scope.ddlConfigProjectsData = ddlData;
            });

            //获取其他产品下拉信息
            contractCommonService.getOtherProducts(function (data) {
                const ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push($.extend({}, {
                        id: d.application_id,
                        text: d.application_name
                    }, d));
                });
                $scope.ddlConfigOtherProjectsData = ddlData;
            });


            //默认合同属性
            $scope.attribute_name_text = ['新增', '混签', '续签', '增购'];
            $scope.attribute_name_arr = ["false", "false", "false", "false"];
            //合同主责人
            $scope.principals = [];
            $scope.showPrincipal = false;

            // 合同性质为
            // “联营签约-云客结算" 7f856e81-fce8-11e4-bed8-00155d02c832
            // "云客签约-联营区域” 7f8422d0-fce8-11e4-bed8-00155d02c832
            // 合同主责人界面隐藏不显示；
            const notShowPrincipalByContractArr = ['7f856e81-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832'];

            //默认合同性质  联营签约-云客结算
            if ($scope.contractBaseInfo.contract_property_id == null) {
                $scope.contractBaseInfo.contract_property_id = "7f856e81-fce8-11e4-bed8-00155d02c832";
            }
            //默认合同类型
            if ($scope.contractBaseInfo.category_id == null) {
                $scope.contractBaseInfo.category_id = "b011f523-fcf2-11e4-bed8-00155d02c832";
            }
            //默认合同大类
            if ($scope.contractBaseInfo.big_category_id == null) {
                $scope.contractBaseInfo.big_category_id = "2ae79470-fcf3-11e4-bed8-00155d02c832";
            }
            //默认小类
            if ($scope.contractBaseInfo.littler_category_id == null) {
                $scope.contractBaseInfo.littler_category_id = "62f81bf4-fcf4-11e4-bed8-00155d02c832";
            }

            //获取合同信息
            $scope.loadContract = function (contractId) {
                if (contractId) {
                    contractCommonService.getContract(contractId, function (data) {
                        //已审核状态
                        $scope.isLimitContractNature = get(data, "contract.contract_status") === 2
                        setTimeout(function () {

                            $scope.contractBaseInfo = data.contract;

                            incomeWithSign(contractId);

                            if ($scope.contractBaseInfo.attribute_name == null) {
                                $scope.contractBaseInfo.attribute_name = "false,false,false,false";
                            }

                            $scope.attribute_name_arr = $scope.contractBaseInfo.attribute_name.split(',');

                            $scope.projects = data.application;
                            $.each($scope.projects, function (i, project) {
                                project.discount_rate = parseFloat(project.discount_rate);
                            })

                            $scope.principals = data.principal;

                            //隐藏合同主责人
                            if (data.contract.contract_property_id != notShowPrincipalByContractArr[0] && data.contract.contract_property_id != notShowPrincipalByContractArr[1]) {
                                $scope.showPrincipal = true;
                            }


                            if (data.contract) {
                                $scope.contractBaseInfo.contract_code_readonly = data.contract.contract_code;
                            }
                            $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({
                                text: data.contract.customer_name || ''
                            });
                            $('#idSigner').length && $('#idSigner').data('select2').updateSelection({
                                text: data.contract.sign_people_name || data.contract.sign_people_id
                            });
                            $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({
                                text: data.contract.company_name || ''
                            });
                            const signDate = moment(data.contract.sign_date, 'YYYY-MM-DD HH:mm:ss');
                            if (signDate.isValid()) {
                                $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                            }
                            const inputDate = moment(data.contract.input_date, 'YYYY-MM-DD HH:mm:ss');
                            if (inputDate.isValid()) {
                                $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                            }
                            const effect_date = moment(data.contract.effect_date, 'YYYY-MM-DD HH:mm:ss');
                            if (effect_date.isValid()) {
                                $scope.contractBaseInfo.effect_date = effect_date.format('YYYY-MM-DD');
                            }
                            $scope.$applyAsync();
                        }, 500);

                    });
                }
            };


            let contractId = $routeParams.id;
            const fromContractId = $routeParams.pid;
            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
                $scope.loadContract(contractId);
            } else if (fromContractId) {
                contractCommonService.getContract(fromContractId, function (data) {
                    setTimeout(function () {
                        $scope.contractBaseInfo = angular.extend(data.contract, {
                            contract_id: null,
                            contract_code: null,
                            input_date: null,
                            balance_status: 0,
                            is_violated: 0,
                            contract_status: 0,
                            is_cancelled: 0
                        });
                        if (data.application) {
                            $.each(data.application, function (i, d) {
                                d['__type'] = 'add';
                            })
                        }
                        $scope.projects = data.application;


                        $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({
                            text: data.contract.customer_name || ''
                        });
                        $('#idSigner').length && $('#idSigner').data('select2').updateSelection({
                            text: data.contract.sign_people_name || data.contract.sign_people_id
                        });
                        $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({
                            text: data.contract.company_name || ''
                        });
                        $scope.generalContractCode();
                        const signDate = moment(data.contract.sign_date, 'YYYY-MM-DD HH:mm:ss');
                        if (signDate.isValid()) {
                            $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                        }
                        const inputDate = moment(data.contract.input_date, 'YYYY-MM-DD HH:mm:ss');
                        if (inputDate.isValid()) {
                            $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                        }
                        $scope.$applyAsync();
                    }, 500);

                });
            }
            function formatCustomer(repo) {
                return repo.text;
            }

            function formatCustomerSelection(repo) {
                return repo.text;
            }
            // 客户下拉框处理
            $scope.ddlConfigCustomer = {
                allowClear: false,
                placeholder: '客户简称',
                ajax: {
                    url: apiPrefix + "erp-interface/get-erp-customer-info",
                    dataType: 'json',
                    delay: 250,
                    data(term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results(json) {
                        let data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                            $.each(data, function (i, d) {
                                d.text = d.CstName;
                                d.id = d.CSTGUID;
                            });
                        }
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                escapeMarkup(markup) {
                    return markup;
                },
                minimumInputLength: 1,
                onchange2(newVal) {
                    $scope.contractBaseInfo.top_customer_name = newVal.DjCstName;
                    $scope.contractBaseInfo.customer_full_name = newVal.CstFullName;
                    $scope.contractBaseInfo.customer_name = newVal.CstName;
                    $scope.contractBaseInfo.customer_code = newVal.CstShortCode;
                },
                formatResult: formatCustomer,
                formatSelection: formatCustomerSelection // omitted for brevity, see the source of this page
            };

            // 合同签约人下拉框处理
            $scope.ddlConfigContractSigner = {
                allowClear: false,
                ajax: {
                    url: apiPrefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data(term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results(json) {
                        let data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {
                            results: data
                        };
                    },
                    processResults(data) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup(markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2(newVal) {
                    $scope.contractBaseInfo.area_name = newVal.BUName;
                    $scope.contractBaseInfo.area_id = newVal.BUGUID;
                    $scope.contractBaseInfo.area_code = newVal.BUCode;
                    $scope.contractBaseInfo.sign_people_department_name = newVal.DepartmentName;
                    $scope.contractBaseInfo.sign_people_department_by = newVal.DepartmentId;
                    $scope.contractBaseInfo.sign_people_abu_name = newVal.AubName;

                    $scope.contractBaseInfo.sign_people_id = newVal.UserGUID;
                    $scope.contractBaseInfo.sign_people_name = newVal.UserName;
                },
                formatResult(repo) {
                    if (repo.loading) return repo.text;

                    const markup = '<div class="clearfix" style="width: 300px;">' +
                        '<div class="clearfix">' +
                        '<div class="col-sm-6">' + repo.UserName + '</div>' +
                        '<div class="col-sm-18">' + repo.BUName + '</div>' +
                        '</div></div>';

                    return markup;
                },
                formatSelection(repo) {
                    return repo.text;
                } // omitted for brevity, see the source of this page
            };

            $scope.ddl2Customer = '';
            $scope.ddl2Type = '';
            $scope.ddl2Company = '';
            $scope.ddl2Category = '';
            $scope.ddl2BigClass = '';
            $scope.ddl2SmallClass = '';
            $scope.ddl2Signer = '';
            $scope.ddl2SignArea = '';
            $scope.ddl2Nature = '';

            const onModal = ({ project, title, readOnly }) => yunkeModal.open({
                title,
                template: editPrincipal,
                controller: "editProjectCtrl",
                resolve: {
                    readOnly,
                    project,
                    ddlConfigOtherProjects: $scope.ddlConfigOtherProjectsData,
                    ddlConfigProjects: $scope.ddlConfigProjectsData,
                    attribute_name_arr: $scope.attribute_name_arr
                }
            })
            //新增/修改产品
            $scope.add = () => onModal({ title: '新增产品' }).promise.then((data) => {
                $scope.projects.push(angular.extend({ __type: 'add', is_standard: '1' }, data));
            })
            $scope.showEdit = function (contractBaseInfo) {
                // const notMYContract = !isSpecial(contractBaseInfo.contract_property_id) //非明源合同
                // return notMYContract ? true : contractBaseInfo.contract_status == 0
                return true
            }
            $scope.update = project => onModal({ project: { ...project }, title: '修改产品' }).promise.then((data) => {
                // const notMYContract = !isSpecial($scope.contractBaseInfo.contract_property_id) //非明源合同
                if (project.__type === 'add') {
                    angular.extend(project, data);
                }
                // 取消限制
                // else if (notMYContract) { }
                else {
                    contractServerName.updateProduct(angular.extend({}, project, { __type: 'update' }, data)).then((res) => angular.extend(project, res.data.data))
                    // angular.extend(project, { __type: 'update' }, data);
                }
            })
            $scope.view = project => onModal({ project, title: '查看产品', readOnly: true })
            $scope.delProject = function (proj) {
                /**
                 * 删除产品
                 */
                util.confirm('确定要删除此产品吗？', {
                    ok() {
                        angular.extend(proj, {
                            __type: 'delete'
                        });
                        $scope.$applyAsync();
                    }
                });
            };

            //新增/修改 合同主责人
            $scope.onPrincipalEditShow = function ($data, $dialog, $dialogScope, oldPrinp) {

                //修改模式下 填充合同主责人;
                if ($data) {
                    setTimeout(function () {
                        $(".principalBy").select2("data", {
                            id: $data.principal_by,
                            text: $data.principal_name
                        });
                    }, 0);
                } else {
                    //默认合同签约人
                    setTimeout(function () {
                        $(".principalBy").select2("data", {
                            id: $scope.contractBaseInfo.sign_people_id,
                            text: $scope.contractBaseInfo.sign_people_name
                        });
                    }, 0);
                    $dialogScope.data.principal_abu_name = $scope.contractBaseInfo.sign_people_abu_name;
                    $dialogScope.data.principal_department_name = $scope.contractBaseInfo.sign_people_department_name;
                    $dialogScope.data.principal_area_name = $scope.contractBaseInfo.area_name;

                    $dialogScope.data.principal_department_by = $scope.contractBaseInfo.sign_people_department_by;
                    $dialogScope.data.principal_area_by = $scope.contractBaseInfo.area_id;

                    $dialogScope.data.principal_by = $scope.contractBaseInfo.sign_people_id;
                    $dialogScope.data.principal_name = $scope.contractBaseInfo.sign_people_name;

                    $dialogScope.data.principal_on = contractCommonService.getCurTime();

                    $dialogScope.data.principal_remark = '合同签约人';
                }
                $dialogScope.oldPrinp = oldPrinp;
                //主责人 下拉框处理
                $dialogScope.ddlConfigPrincipal = {
                    allowClear: false,
                    ajax: {
                        url: apiPrefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data(term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results(json) {
                            let data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {
                                results: data
                            };
                        },
                        processResults(data) {
                            // parse the results into the format expected by Select2.
                            // since we are using custom formatting functions we do not need to
                            // alter the remote JSON data
                            return {
                                results: data.items
                            };
                        },
                        cache: true
                    },
                    escapeMarkup(markup) {
                        return markup;
                    }, // let our custom formatter work
                    minimumInputLength: 1,
                    onchange2(newVal) {
                        $dialogScope.data.principal_abu_by = newVal.AubGUID;
                        $dialogScope.data.principal_abu_name = newVal.AubName;
                        $dialogScope.data.principal_department_by = newVal.DepartmentId;
                        $dialogScope.data.principal_department_name = newVal.DepartmentName;
                        $dialogScope.data.principal_area_by = newVal.BUGUID;
                        $dialogScope.data.principal_area_name = newVal.BUName;
                        $dialogScope.data.principal_name = newVal.UserName;
                    }
                };


            }


            /**
             * 判断查询时间
             * @param a
             * @param b
             * @returns {boolean}
             */
            const compareDate = function (a, b) {
                const arrA = a.split("-");
                const start = new Date(arrA[0], arrA[1], arrA[2]);
                const startTime = start.getTime();

                const arrB = b.split("-");
                const end = new Date(arrB[0], arrB[1], arrB[2]);
                const endTime = end.getTime();

                if (startTime > endTime) {
                    return true
                }
                return false
            };

            $scope.addContractPrincipal = function ($data) {
                $scope.principals.push($.extend({
                    __type: 'add'
                }, $data));
            };
            $scope.saveContractPrincipal = function ($data, $dialog, $dialogScope) {
                const start = $dialogScope.data.principal_on;
                const end = $dialogScope.data.principal_end;


                if (end && end != '' && compareDate(start, end)) {
                    util.alert('截止时间不能超过生效时间!')
                    return false;
                }


                angular.extend($dialogScope.oldPrinp, $.extend({
                    __type: 'update'
                }, $data));

            };
            $scope.delPrincipal = function (proj) {
                /**
                 * 删除
                 */
                util.confirm('确定要删除此合同主责人吗？', {
                    ok() {
                        angular.extend(proj, {
                            __type: 'delete'
                        });
                        $scope.$applyAsync();
                    }
                });

            };


            //监听合同性质
            $scope.$watch('contractBaseInfo.contract_property_id', function (newData) {
                if (newData) {
                    if (newData == notShowPrincipalByContractArr[0] || newData == notShowPrincipalByContractArr[1]) {
                        $scope.showPrincipal = false;
                    } else {
                        $scope.showPrincipal = true;
                    }
                }
            })


            $scope.$watch('contractBaseInfo.sign_amount', function () {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.rent_amount', function () {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.delivery_amount', function () {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.rent_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.delivery_amount);
                }
            });

            //检测 生成合同编号
            $scope.$watch('contractBaseInfo.customer_id', function () {
                $scope.generalContractCode();
            });
            $scope.$watch('contractBaseInfo.area_code', function () {
                $scope.generalContractCode();
            });
            $scope.$watch('contractBaseInfo.sign_people_department_by', function () {
                $scope.generalContractCode();
            });
            $scope.generalContractCode = function () {
                if ($scope.contractBaseInfo.customer_code && $scope.contractBaseInfo.area_code) {
                    contractCommonService.genContractFlowCode($scope.contractBaseInfo.area_code, $scope.contractBaseInfo.customer_code,
                        $scope.contractBaseInfo.contract_code,
                        function (data) {
                            $scope.contractBaseInfo.contract_code = data;
                            $scope.$applyAsync();
                        });
                }
            };


            $scope.save = function () {
                const isNew = !contractId;
                //合同性质为明源签约-直属区域, 云客签约-直属区域时,合同主责人必填
                const needPrincipalsByContractArr = ['54f8a2b7-fce7-11e4-bed8-00155d02c832', '7f83719a-fce8-11e4-bed8-00155d02c832'];


                //复选框数组转换成字符串
                $scope.contractBaseInfo.attribute_name = $scope.attribute_name_arr.toString();

                //收集合同信息
                const baseInfo = $scope.contractBaseInfo;
                const projectsInfo = $scope.projects;
                const principalInfo = $scope.principals;

                if (includes(needPrincipalsByContractArr, baseInfo.contract_property_id)) {
                    if (principalInfo.length <= 0) {
                        util.alert('合同性质为 明源签约-直属区域 / 云客签约-直属区域 时, 合同主责人必填!')
                        return false;
                    }
                }

                const url = `${apiPrefix}${isNew ? "/contract/add-contract" : "/contract/update-contract"}`

                util.myAjax({
                    url,
                    type: "POST",
                    context: this,
                    data: {
                        contract: baseInfo,
                        product: projectsInfo,
                        principal: principalInfo
                    },
                    success(json) {
                        if (json.retCode === "0") {
                            if (isNew) {
                                $location.path("base").search({
                                    id: json.data
                                });
                                contractId = json.data;
                                setTimeout(function () {
                                    location.reload()
                                    // side.refresh();
                                }, 1000);
                                util.alert('合同创建成功', {
                                    ok() {
                                        setTimeout(function () {
                                            // side.refresh();
                                            location.reload()
                                        }, 500);
                                    }
                                });
                            } else {
                                util.alert("保存成功");
                            }
                            $scope.loadContract(contractId);
                        } else {
                            util.alert(`保存失败：${json.errMsg}`);
                        }
                    }
                });
            };

            $scope.verify = function () {
                /**
                 * 提交复核
                 */

            }
        }])
    .controller('editProjectCtrl', [
        '$scope', 'project',
        'attribute_name_arr', 'ddlConfigOtherProjects', 'ddlConfigProjects', 'modalInstance', 'readOnly', '$timeout',
        ($scope, oldProd, attributeNameArr, ddlConfigOtherProjects, ddlConfigProjects, instance, readOnly, timeout) => {
            function setUp() {
                $scope.oldProd = oldProd;
                $scope.readOnly = readOnly
                $scope.isEdit = get(oldProd, "contract_application_id")
                $scope.data = oldProd || {}
                if (!$scope.data.discount_rate) {
                    $scope.data.discount_rate = 1;
                }
                //项目数
                $scope.$watch('data.authorization_numeric', function (itemVal) {
                    if ($scope.data.authorization_type === 0 && $scope.data.is_simple !== 1) {
                        const period = $scope.data.rent_period || 0;
                        const discount = parseFloat($scope.data.discount_rate) || 1;
                        $scope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul(itemVal, period), discount), $scope.data.price), 12));
                    }
                });
                //项目周期
                $scope.$watch('data.rent_period', function (itemVal) {
                    if ($scope.data.authorization_type == 0 && $scope.data.is_simple != 1) {
                        const number = $scope.data.authorization_numeric || 0;
                        const discount = parseFloat($scope.data.discount_rate) || 1;
                        $scope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul(itemVal, number), discount), $scope.data.price), 12));
                    }
                });
                //免费短信金额为0，不允许修改
                $scope.$watch('data.price', function (itemVal) {
                    if (parseFloat(itemVal) == 0) {
                        $scope.data.amount = 0;
                    }
                    if ($scope.data.application_id == "other") {
                        const number = $scope.data.authorization_numeric || 0;
                        const period = $scope.data.rent_period || 0;
                        $scope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul(number, period), 1), itemVal), 12));
                    }
                })

                $scope.ddlConfigContractType = {
                    allowClear: false,
                    data: contractType,
                    placeholder: '合同属性',
                    onchange2(ct) {
                        $scope.data.contract_type = ct.id;
                    }
                };

                //如果是新增，合同属性取基本信息中的
                if (oldProd === undefined) {
                    //合同属性
                    const isXz = attributeNameArr[0] === "true";
                    const isHq = attributeNameArr[1] === "true";
                    const isXq = attributeNameArr[2] === "true";
                    let isZg = false;
                    if (attributeNameArr.length === 4) {
                        isZg = attributeNameArr[3] === "true";
                    }
                    if (isXz && !isHq && !isXq && !isZg) {
                        $scope.data.contract_type = 1;
                    }
                    if (!isXz && !isHq && !isXq && isZg) {
                        $scope.data.contract_type = 2;
                    }
                    if (!isXz && !isHq && isXq && !isZg) {
                        $scope.data.contract_type = 3;
                    }
                    //新增时如果不自定义结算标准价，则默认等于标准金额
                    $scope.$watch('data.amount', function (itemVal) {
                        $scope.data.benchmark_amount = $scope.data.amount
                    })
                }

                $scope.ddlConfigProjects = {
                    allowClear: false,
                    data: ddlConfigProjects,
                    placeholder: '产品名称',
                    onchange2(item, godKnow, oldValue) {
                        $scope.data.authorization_type = item.authorization_type;
                        $scope.data.application_name = item.application_name;
                        $scope.data.application_id = item.application_id;
                        $scope.data.unique_name = item.unique_name;
                        $scope.data.is_simple = item.is_simple;
                        if (!isEmpty(oldValue)) {
                            $scope.data.amount = ""
                            $scope.data.price = ""
                        }
                        if (item.authorization_type == 0 && item.applicationPrices.length) {
                            $scope.data.price = item.applicationPrices[0].price;
                            const period = $scope.data.rent_period || 0;
                            const discount = parseFloat($scope.data.discount_rate) || 1;
                            $scope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul($scope.data.authorization_numeric, period), discount), $scope.data.price), 12));
                        }

                        $scope.ddlConfigSMSPrice = {
                            allowClear: false,
                            data: map(item.applicationPrices, ({ price, unit }) => ({
                                id: price,
                                text: unit
                            })),
                            placeholder: '标准单价',
                            onchange2(price) {
                                $scope.data.unit = price.text;
                            }
                        };

                        $scope.$applyAsync();
                    }
                };

                //产品明细
                $scope.ddlConfigOtherProjects = {
                    allowClear: false,
                    data: ddlConfigOtherProjects,
                    placeholder: '其他产品',
                    onchange2(item) {
                        $scope.data.other_application_name = item.application_name;
                        $scope.data.other_application_id = item.application_id
                    }
                };
                //结算类型
                $scope.ddlConfigSettlementType = {
                    allowClear: false,
                    data: settlementType,
                    placeholder: '结算类型',
                    onchange2(_settlementType) {
                        $scope.data.settlement_type = _settlementType.id;
                    }
                };
                $scope.onResolve = () => {
                    instance.resolve($scope.data)
                }
                $scope.onReject = () => {
                    instance.reject("取消")
                }
            }
            timeout(setUp, 0);
        }])
    .filter('sumProductAmount', function () {
        return function (products) {
            let amount = 0;
            $.each(products, function (i, d) {
                if (d.__type == 'delete') {
                    return;
                }
                amount = myMath.add(amount, d.amount);
            });
            return amount;
        };
    })
    .filter('shareAmount', ['$filter', function ($filter) {
        return function (product, products, rentAmount) {
            const productAmount = $filter('sumProductAmount')(products);

            //（标准总额/产品标准总额合计）*产品租用金额
            if (productAmount == 0) {
                return 0;
            }

            return (product.amount / productAmount) * rentAmount;
        };
    }])
    .filter('countSMS', function () {
        return function (products) {
            let num = 0;
            $.each(products, function (i, d) {
                if (d.__type == 'delete') {
                    return;
                }
                num = myMath.add(num, d.authorization_type == 1 ? d.authorization_numeric : 0);
            });
            return num;
        };
    })
    .filter('countProject', function () {
        return function (products) {
            let num = 0;
            $.each(products, function (i, d) {
                if (d.__type == 'delete') {
                    return;
                }
                num = myMath.add(num, d.authorization_type == 0 ? d.authorization_numeric : 0);
            });
            return num;
        };
    })
    .filter('getContractTypeName', function () {
        return function (_contractType) {
            _contractType = parseInt(_contractType, 10);
            let name = "";
            switch (_contractType) {
                case 1:
                    name = "新增";
                    break;
                case 2:
                    name = "增购";
                    break;
                case 3:
                    name = "续签";
                    break;
                default:
                    name = ""
            }
            return name;
        };
    })
    .filter('financialFrom', () => {
        const maps = {
            '54f8a2b7-fce7-11e4-bed8-00155d02c832': '直销合同', // 明源签约-直属
            '7f828b1b-fce8-11e4-bed8-00155d02c832': '直销合同', //明源签约-联营
            '7f83719a-fce8-11e4-bed8-00155d02c832': '直销合同', // 云客签约-直属
            '7f8422d0-fce8-11e4-bed8-00155d02c832': '直销合同', // 云客签约-联营
            '7f856e81-fce8-11e4-bed8-00155d02c832': '分销合同', // 联营签约-云客结算
            'efa353cd-51ca-11e8-a035-00155d02c83e': '直销合同', // 云客直销
        };
        return x => maps[x];
    })
    .filter('businessFrom', () => {
        const maps = {
            '54f8a2b7-fce7-11e4-bed8-00155d02c832': '直销合同', // 明源签约-直属
            '7f828b1b-fce8-11e4-bed8-00155d02c832': '分销合同', //明源签约-联营
            '7f83719a-fce8-11e4-bed8-00155d02c832': '直销合同', // 云客签约-直属
            '7f8422d0-fce8-11e4-bed8-00155d02c832': '分销合同', // 云客签约-联营
            '7f856e81-fce8-11e4-bed8-00155d02c832': '分销合同', // 联营签约-云客结算
            'efa353cd-51ca-11e8-a035-00155d02c83e': '云客直销', // 云客直销
        };
        return x => maps[x];
    });
